#!/usr/bin/python
import os
import sys
import commands
from ROOT import TFile,TH1,TTree,TIter,TKey

inputHist='mc12.lailin.prw.root'
tf=TFile(inputHist)
list_hist=tf.GetListOfKeys()
next=TIter(tf.GetListOfKeys())

dict_hist={}
### read hist information
for i in range(list_hist.GetSize()):
  key=next.Next()
  obj=key.ReadObj()
  if obj.IsA().InheritsFrom(TH1.Class()):
    hname=obj.GetName()
    entry=obj.GetEntries()
    mean=obj.GetMean()
    mcid=hname.split('_')[1].split('chan')[1]
    if not mcid in dict_hist.keys():
      dict_hist[mcid]={}
    dict_hist[mcid]['entry']=entry
    dict_hist[mcid]['mean']=mean

### read dataset name
listmc='new_list_mc'
fin=open(listmc, 'r')
for lines in fin.readlines():
  if lines[-1]=='\n': line=lines[:-1]
  else: line=lines
  if len(line)==0: continue
  mcid=line.split('.')[1]
  if not mcid in dict_hist.keys():
    dict_hist[mcid]={}
    print 'new mcid: ', mcid
    dict_hist[mcid]['entry']=0
    dict_hist[mcid]['mean']=0
  dict_hist[mcid]['dataset']=line


### check AMI 
output='list_to_rerun'
fout=open(output, 'w')

for mcid in dict_hist.keys():
  dataset=dict_hist[mcid]['dataset']
  if dict_hist[mcid]['mean'] < 10:
    print 'wrong info: ', dataset, ' mean: ', dict_hist[mcid]['mean']
    fout.write('%s\n' % dataset)
  cmd='ami dataset info '+dataset+" | grep totalEvents | awk '{print $2}' "
  totEvents=commands.getoutput(cmd)
  dict_hist[mcid]['totEvents']=float(totEvents)
  if dict_hist[mcid]['totEvents'] > dict_hist[mcid]['entry']:
    print 'events missed: ', dataset, ' totEvents: ', dict_hist[mcid]['totEvents'], ' entries: ', dict_hist[mcid]['entry']
    fout.write('%s\n' % dataset)
